﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DeviceMonitor.Classes.Model;
using DeviceMonitor.Model;
using DeviceMonitor.ViewModel;
using DeviceMonitor;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Threading;
using DeviceMonitor.Utils;
using DeviceMonitor.Classes;
using DeviceMonitor.Dao;

namespace WpfApplication1.Classes
{
    public class MessageDeal
    {
        public static void DealMessage62(int index, Message62 message)
        {
            DeviceGroupModel deviceGroup = App.GetDeviceGroups()[index];
            String id = message.Id.ToString();
            if (!deviceGroup.devicesTable.ContainsKey(id))
            {
                return;
            }
            DeviceModel device = deviceGroup.devices[(int)deviceGroup.devicesTable[id]];

            device.Id = message.Id;

            if ("等待验卡".Equals(message.CheckStatus))
            {
                //验卡
                if ("1".Equals(App.GetConfig().CheckCard))
                {
                    CheckCard(message);
                }
            }

            if (device.OrderCode == null || !device.OrderCode.Equals(message.OrderCode))
            {
                //开始发油
                device.OrderCode = message.OrderCode;
                string sendMessage = App.GetConfig().sendMessage;
                if (!"".Equals(App.GetConfig().HttpServerIp))
                {
                    if ("true".Equals(sendMessage))
                    {
                        GetProductAndCarNo(message);
                        device.Product = message.Product;
                        device.CarNo = message.CarNo;
                    }
                }
                else
                {
                    device.Product = "";
                    device.CarNo = "";
                }
            }
            message.Product = device.Product;
            message.CarNo = device.CarNo;

            string _oldAlerm = device.Alerm==null ? "00000000" : device.Alerm;
            _oldAlerm = _oldAlerm.PadLeft(8, '0');
            if (!_oldAlerm.Equals(message.Alerm))
            {
                //报警发生变化,处理报警
                //DealAlerm(_oldAlerm, message.Alerm, device, message.ServiceIndex.ToString(), message.OrderCode);
            }
        }

        public static void DealMessage63(int index, Message63 message)
        {
            DeviceGroupModel deviceGroup = App.GetDeviceGroups()[index];
            String id = message.Id.ToString();
            if (!deviceGroup.devicesTable.ContainsKey(id))
            {
                return;
            }
            DeviceModel device = deviceGroup.devices[(int)deviceGroup.devicesTable[id]];

            device.Id = message.Id;

            //恢复报警
            device.Alerm = "00000000";
            device.AlermDealStatus = "00000000";

            saveAllDealAlerm(message.ServiceIndex.ToString(), message.Id.ToString());

            String deviceOrderCode = device.OrderCode == null ? "" : device.OrderCode;

            if (deviceOrderCode.Equals(message.OrderCode))
            {
                device.OrderCode = "";

                //上传发油记录 todo

                
            }
        }

        public static void DealMessage6804(int index, Message68 message)
        {
            
        }
        public static void DealMessage6805(int index, Message68 message)
        {
            
        }
    
        private static void DealAlerm(String oldAlerm, String newAlerm, DeviceModel device, String groupCode, String billNo)
        {
            if (device.AlermDealStatus == null)
            {
                device.AlermDealStatus = "";
            }
            device.AlermDealStatus = device.AlermDealStatus.PadLeft(8, '0');
            string messageDealSetting = App.GetConfig().messageDealSetting;
            String dealStatus = "";
            for(int i=0; i<8; i++)
            {
                String oldVal = oldAlerm.Substring(i, 1);
                String newVal = newAlerm.Substring(i, 1);
                String dealVal = device.AlermDealStatus.Substring(i, 1);
                String isDeal = messageDealSetting.Substring(i, 1);

                if ("0".Equals(isDeal)) continue;

                if ("1".Equals(newVal) && "0".Equals(dealVal))
                {
                    //有报警,未处理,deal->1
                    Console.WriteLine("id:" + device.Id + " errorIdx:" + i + " deal --> 1");
                    dealStatus += "1";

                    string alermId = i.ToString();
                    string alermName = "";
                    if (App.GetConfig().alermNameMap.ContainsKey(alermId))
                    {
                        alermName = (string)App.GetConfig().alermNameMap[alermId];
                    }
                    saveNewAlerm(groupCode, device.code, alermId, alermName, billNo);
                }
                else if ("0".Equals(newVal) && "1".Equals(dealVal))
                {
                    //报警,已处理,deal->0
                    dealStatus += "0";
                    Console.WriteLine("id:" + device.Id + " errorIdx:" + i + " deal --> 0");

                    string alermId = i.ToString();
                    saveDealAlerm(groupCode, device.code, alermId);
                }
                else
                {
                    dealStatus += dealVal;
                }
            }
            device.Alerm = newAlerm;
            device.AlermDealStatus = dealStatus;
        }
    
        private static void CheckCard(Message62 message)
        {
            new Thread(() =>
            {
                try
                {
                    JObject paramJSON = new JObject();
                    paramJSON.Add("billNo", message.OrderCode);
                    paramJSON.Add("loadPlaceId", message.Id);

                    String response = HttpPostHelper.doHttpPost("/ytBill/yifayouJudgeNew", paramJSON.ToString());
                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "200")
                    {
                        string cmd = MessageUtils.getCardCheckSuccessMessage(message.Id);
                        CanBusNet canBusNet = App.GetCanBusNetList()[message.ServiceIndex];
                        canBusNet.SendData(cmd, true);

                        Console.WriteLine("发送验卡成功");
                    }
                    else
                    {
                        string cmd = MessageUtils.getCardCheckErrorMessage(message.Id);
                        CanBusNet canBusNet = App.GetCanBusNetList()[message.ServiceIndex];
                        canBusNet.SendData(cmd, true);

                        Console.WriteLine("发送验卡失败");
                    }
                }
                catch{}
            }).Start();
        }

        private static void GetProductAndCarNo(Message62 message)
        {
            try
            {
                JObject paramJSON = new JObject();
                paramJSON.Add("billNo", message.OrderCode);

                String response = HttpPostHelper.doHttpPost("/ytBill/getBillInfo", paramJSON.ToString());
                JObject respJson = JObject.Parse(response);
                string status = respJson["code"].ToString();
                if (status.ToLower() == "200")
                {
                    message.Product = respJson["product"].ToString();
                    message.CarNo = respJson["carNo"].ToString();
                }
            }
            catch { }
        }

        private static void saveNewAlerm(string groupCode, string code, string alerm, string alermName, string billNo)
        {
            /*
            new Thread(() =>
            {
                try
                {
                    String id = (String)SqlMapDao.instance().QueryForObject("selectUUID", null);
                    AlermModel alermModel = new AlermModel();
                    alermModel.id = id;
                    alermModel.groupCode = groupCode;
                    alermModel.code = code;
                    alermModel.alerm = alerm;
                    alermModel.alermName = alermName;
                    alermModel.billNo = billNo;

                    SqlMapDao.instance().Insert("insertAlerm", alermModel);
                }
                catch (Exception e){
                    Console.WriteLine(e.ToString());
                }
            }).Start();*/
        }
        private static void saveDealAlerm(string groupCode, string code, string alerm)
        {
            new Thread(() =>
            {
                try
                {
                    Hashtable paramTable = new Hashtable();
                    paramTable.Add("groupCode", groupCode);
                    paramTable.Add("code", code);
                    paramTable.Add("alerm", alerm);

                    AlermModel alermModel = (AlermModel)SqlMapDao.instance().QueryForObject("selectNoDealAlerm", paramTable);

                    if (null != alermModel)
                    {
                        SqlMapDao.instance().Update("updateAlermDeal", alermModel);
                    }
                }
                catch { }
            }).Start();
        }
        private static void saveAllDealAlerm(string groupCode, string code)
        {
            /*
            new Thread(() =>
            {
                try
                {
                    AlermModel alermModel = new AlermModel();
                    alermModel.groupCode = groupCode;
                    alermModel.code = code;

                    SqlMapDao.instance().Update("updateAlermAllDeal", alermModel);
                }
                catch { }
            }).Start();*/
        }
    }
}
